package com.witmore.neutron.ai.web.apiv2.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jk.common.response.PageInfo;
import com.jk.common.response.ResponsePageResult;
import com.witmore.neutron.ai.db.entity.UserRechargeRecordDO;
import com.witmore.neutron.ai.db.entity.UserUsageDetailDO;
import com.witmore.neutron.ai.db.mapper.UserRechargeRecordMapper;
import com.witmore.neutron.ai.db.mapper.UserUsageDetailMapper;
import com.witmore.neutron.ai.web.annotation.RequiresPermission;
import com.witmore.neutron.ai.web.controller.vo.*;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户记录控制器
 * 包含用户充值记录和使用详情的查询接口
 *
 * @author 豆子高
 * @since 2025-09-10
 */
@RestController
@RequestMapping("/v2/user/record")
public class UserRecordController {

    @Autowired
    private UserRechargeRecordMapper userRechargeRecordMapper;

    @Autowired
    private UserUsageDetailMapper userUsageDetailMapper;

    /**
     * 用户充值记录列表查询（分页）
     */
    @RequiresPermission("user:recharge:list")
    @GetMapping("/recharge/list")
    public ResponsePageResult<UserRechargeRecordVO> getRechargeRecordList(@Valid UserRechargeRecordQuery query) {
        // 构建查询条件
        LambdaQueryWrapper<UserRechargeRecordDO> queryWrapper = new LambdaQueryWrapper<UserRechargeRecordDO>()
                .like(StringUtils.hasText(query.getUserName()), UserRechargeRecordDO::getUserName, query.getUserName())
                .eq(query.getOperationType() != null, UserRechargeRecordDO::getOperationType, query.getOperationType())
                .ge(query.getOperationTimeStart() != null, UserRechargeRecordDO::getCreateTime, query.getOperationTimeStart())
                .le(query.getOperationTimeEnd() != null, UserRechargeRecordDO::getCreateTime, query.getOperationTimeEnd())
                .orderByDesc(UserRechargeRecordDO::getCreateTime);

        // 分页查询
        Page<UserRechargeRecordDO> page = userRechargeRecordMapper.selectPage(
                new Page<>(query.getPage(), query.getSize()),
                queryWrapper
        );

        if (page.getRecords().isEmpty()) {
            return ResponsePageResult.success(new ArrayList<>(),
                    new PageInfo(query.getPage(), query.getSize(), 0L, 0L));
        }

        // 转换为VO
        List<UserRechargeRecordVO> recordVOs = new ArrayList<>();
        for (UserRechargeRecordDO record : page.getRecords()) {
            UserRechargeRecordVO vo = new UserRechargeRecordVO();
            BeanUtils.copyProperties(record, vo);

            // 设置操作类型描述
            if (record.getOperationType() != null) {
                vo.setOperationTypeDesc(record.getOperationType() == 1 ? "充值" : "扣款");
            }

            recordVOs.add(vo);
        }

        // 构建返回结果
        PageInfo pageInfo = new PageInfo(query.getPage(), query.getSize(),
                page.getTotal(), page.getPages());

        return ResponsePageResult.success(recordVOs, pageInfo);
    }

    /**
     * 用户使用详情列表查询（分页）
     */
    @RequiresPermission("user:usage:list")
    @GetMapping("/usage/list")
    public ResponsePageResult<UserUsageDetailVO> getUsageDetailList(@Valid UserUsageDetailQuery query) {
        // 构建查询条件
        LambdaQueryWrapper<UserUsageDetailDO> queryWrapper = new LambdaQueryWrapper<UserUsageDetailDO>()
                .eq(StringUtils.hasText(query.getSessionId()), UserUsageDetailDO::getSessionId, query.getSessionId())
                .eq(StringUtils.hasText(query.getUserApiKey()), UserUsageDetailDO::getUserApiKey, query.getUserApiKey())
                .eq(StringUtils.hasText(query.getRowMetadataId()), UserUsageDetailDO::getRowMetadataId, query.getRowMetadataId())
                .eq(query.getProviderId() != null, UserUsageDetailDO::getProviderId, query.getProviderId())
                .eq(query.getAgentId() != null, UserUsageDetailDO::getAgentId, query.getAgentId())
                .ge(query.getCreateTimeStart() != null, UserUsageDetailDO::getCreateTime, query.getCreateTimeStart())
                .le(query.getCreateTimeEnd() != null, UserUsageDetailDO::getCreateTime, query.getCreateTimeEnd())
                .orderByDesc(UserUsageDetailDO::getCreateTime);

        // 分页查询
        Page<UserUsageDetailDO> page = userUsageDetailMapper.selectPage(
                new Page<>(query.getPage(), query.getSize()),
                queryWrapper
        );

        if (page.getRecords().isEmpty()) {
            return ResponsePageResult.success(new ArrayList<>(),
                    new PageInfo(query.getPage(), query.getSize(), 0L, 0L));
        }

        // 转换为VO
        List<UserUsageDetailVO> detailVOs = new ArrayList<>();
        for (UserUsageDetailDO detail : page.getRecords()) {
            UserUsageDetailVO vo = new UserUsageDetailVO();
            BeanUtils.copyProperties(detail, vo);
            detailVOs.add(vo);
        }

        // 构建返回结果
        PageInfo pageInfo = new PageInfo(query.getPage(), query.getSize(),
                page.getTotal(), page.getPages());

        return ResponsePageResult.success(detailVOs, pageInfo);
    }
}
